# --*--coding=utf-8 --*--
"""
构建相应代理类
"""
from xml.dom import minidom
from auto_test.config import CBSConfig
from auto_test.test.parse.parse_data import getCbcProxyMsgByNameAndBankType
import socketserver


class ProxySocketServer(socketserver.BaseRequestHandler):
    """
    CBC服务器的代理服务
    """

    def handle(self):
        """
        处理请求
        """
        while True:
            try:
                rec_data = self.request.recv(10240)
                rec_data = str(rec_data, encoding='gbk')
                # print(rec_data)
                xmlParser = minidom.parseString(rec_data)
                msg_bank_type, msg_name = None, None
                for sect_ele in xmlParser.getElementsByTagName('Section'):
                    if sect_ele.getAttribute('SectionName') != 'DCCOMSECX':
                        continue
                    for prop_ele in sect_ele.getElementsByTagName('elXmlProperty'):
                        for attr_ele in prop_ele.getElementsByTagName('Attribute'):
                            if attr_ele.getAttribute('key') == 'BNKTYP':
                                msg_bank_type = attr_ele.getAttribute('value')
                            if attr_ele.getAttribute('key') == 'BUSTYP':
                                msg_name = attr_ele.getAttribute('value')
                if msg_bank_type is None or msg_name is None:
                    continue
                # print(msg_name, msg_bank_type)
                proxyMsg = getCbcProxyMsgByNameAndBankType(msg_name, msg_bank_type)
                # print(proxyMsg.msg_path)
                if proxyMsg is not None:
                    f = open(proxyMsg.msg_path, encoding='gbk')
                    self.request.sendall(bytes(f.read(), encoding='GBK'))
            except Exception as e:
                print(e)
                # break


def start_cbc_proxy():
    """
    启动代理服务器
    """
    ip = CBSConfig.CBC_PROXY_SERVER_IP
    port = CBSConfig.CBC_PROXY_SERVER_PORT
    s = socketserver.ThreadingTCPServer((ip, port), ProxySocketServer)
    s.serve_forever()


if __name__ == '__main__':
    start_cbc_proxy()
